package com.example.seh.home.pay;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.example.seh.MainActivity;
import com.example.seh.R;
import com.example.seh.chat.Msg;
import com.example.seh.constant.Constant;
import com.example.seh.home.OrderDTO;
import com.example.seh.home.pay.util.OrderInfoUtil2_0;
import com.example.seh.home.secondhand.GoodsBuyActivity;
import com.example.seh.home.substitution.CourierSuccessActivity;
import com.example.seh.person.ListenerManager;
import com.example.seh.util.BackUtil;
import com.example.seh.util.LoginActivity;
import com.example.seh.util.UserMsg;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PayActivity extends AppCompatActivity {
    private TextView wait, result, payPrice;
    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "9021000122685805";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "2088722004053465";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "rgidxo0912@sandbox.com";

    /**
     *  pkcs8 格式的商户私钥。
     *
     * 	如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 	使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * 	RSA2_PRIVATE。
     *
     * 	建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 	工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCJ/7VCuV6YFeq1bPrZLFnJ+zOAXCkMtobKNjWGhAXx4fg6no8mtdhz3XzbeBthVuK3q+mBevDpn6g/huZwckTxVl5B8RXZr8iVcCYBxxP4upfi/pn/OxzI9sUhfUnpAmbwqGpuCDGghQqKndRg24XOPku8KvSAKbjqJCBlwYLJZcGgfIE4An7fS9qRByV61u+PZTtVNsMZo85no6JVRkDUkpoUu8qjysYG8XNOHkVk4Pvh2/sFJnYB+IBICdp+qX8vAvrr7HoFPFywAQZ73c7j6VWndfdEu69O4hjosItFKX3K2kNKM3M5zOafSdrLin9dcCwSWe0q3iHgmUKN1NwxAgMBAAECggEAa/21hU+23OFZ2Tw9WbJBWbTA6tQ0M4SrGpctb+TlGhKxxH3MnIh1qMZNLRpiotvxc7aOdwsUeF6+tWgF8T0bApmKDaRyavYKzBcFRyLZWC39Kl//dyJ1NjcWsUxwiG2ezPmewBidbXZvd2Znipx/q5RIhCpBSAJeeKxoxfiXNq7KZPu55S+y5F23xn6XAhHoeU7snT8NU3x2V/RObTJTck+pyO4EZNv4p6BFFVT3GkyNUJmSenJAs2SCu57KdVLKB6sxlTLKlaulhJpX1s//dv6BPar/7ZRyNfs/0oJMwWSn64IPoS3IIQYD0dmD3M+ECGyODGh+g6s578vPhbSEAQKBgQDDDTssuvP5aYbT2mIKqlJMu8nVcHMrwPqo6f45XcP82UKap9vlfA7rGbP3gMDDiGz7eZ+uGgmFURt+QKHg5LKw5QtqHqVoNlc1vcY9+CX2/0pCuBCVQzTRyrTo9IZbVz0yrLxd2oMO/1a02x8ikuBWXMEKk1MTJ8ONZjY+PQtG4QKBgQC1HqaEA5zcoh9BA7QkWGAVsAUSJ0YjmRqBw4P5aqvxPMwE2mvsXmPip98/k0rld68iWrlLjPUhntZoi8vRIPsm2Q+CWBzPxtuDK4i4WxtvRhkJtbOktgWS0dQq9p68MgBpvtEjtJswym3dOpx632185F5k42AghdsCPRS94uRPUQKBgF2RqFSB7u40CGDy/1tcb5St9Vn10tonflevwKwmZhGS69ejNOL2y3VO5D2UP2TNunI82zQ6+1xAF29OdBmdvHcNuZcT0oeWoel++23Y7+V4fFhbUmE4V0tY8cZbH2UMCaiYothnLb3xEdg60cnVKddkMZrwJ8clqTLY2KasxA8hAoGAX5rYRuMpUAV7/fOYiX7k6U3Kv3Rfv7a3mTu9VFEMhgCTqRQq19BTZXc7jvGPHWV52uaM3OaBFsgjYXg5lCCWskDtwN4GB19uy+SU/MuKxcf4u3lgZFd4xbFhD3SzAaBbO3ZwKyrQqIaSS67+npWF0+EwOo0TVteRbbMUWc+EuKECgYA/rvwU7nDro/qdkrWhyU7SSWjoXcFCFOXPBJK3PXnnFZ2m6rXv03NODZAPne0oGOwvKtJMBCej9WeO54L3UwwhLnAUhZEOlI7jjs3c4u7aPTPlohPAtR9+y+zwmOeufls/locCfuhGPqY5hpICfRHQ9wUacDesJsQhLpKCuT233A==";
    public static final String RSA_PRIVATE = "";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private static final int SDK_PAY_RESULT = 3;
    private static final int SDK_PAY_FAIL = 4;
    private static final int SDK_PAY_SUCCESS = 5;
    private String orderId="";
    private OrderDTO orderDTO;
    private double price;
    private TextView num, txt;
    private int count;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //保存该订单
//                        savaOrder();
                        paySuccess();
//                        showAlert(PayActivity.this, getString(R.string.pay_success) + payResult);
                    } else {
                        delOrder();

//                        showAlert(PayActivity.this, getString(R.string.pay_failed) + payResult);
                    }

                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        showAlert(PayActivity.this, getString(R.string.auth_success) + authResult);
                    } else {
                        // 其他状态值则为授权失败
                        showAlert(PayActivity.this, getString(R.string.auth_failed) + authResult);
                    }
                    break;
                }
                case SDK_PAY_RESULT:
//                    payResult();
                    payV2();
                    break;
                case SDK_PAY_FAIL:
                    payFail();
                default:
                    break;
            }
        };
    };




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        wait = findViewById(R.id.pay_wait);
        result = findViewById(R.id.pay_success);
        payPrice = findViewById(R.id.pay_price);
        num = findViewById(R.id.pay_num);
        txt = findViewById(R.id.pay_txt);

        Intent intent = getIntent();
        orderDTO = (OrderDTO) intent.getSerializableExtra("order");
        if (orderDTO != null) {
            price = orderDTO.getOrderPrice();
        }

        savaOrder();
//        payV2();
    }
    private void delOrder() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.UPDATE_ORDER_STATUS + orderId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("pay", "回退订单状态：" + result);

            }
        });
        wait.setVisibility(View.INVISIBLE);
        result.setVisibility(View.VISIBLE);
        result.setText("支付失败");

        num.setVisibility(View.VISIBLE);
        txt.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 3; i >= 0; i--) {
                    count = i;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (count > 0) {
                                num.setText(count + "");
                            } else {
                                finish();
                            }

                        }
                    });
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    private void paySuccess() {
        wait.setVisibility(View.INVISIBLE);
        result.setVisibility(View.VISIBLE);
        result.setText("支付成功");
        payPrice.setVisibility(View.VISIBLE);
        payPrice.setText(orderDTO.getOrderPrice() + " ￥");

        num.setVisibility(View.VISIBLE);
        txt.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 3; i >= 0; i--) {
                    count = i;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (count > 0) {
                                num.setText(count + "");
                            } else {
                                Intent intent = new Intent(PayActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            }

                        }
                    });
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        ListenerManager listenerManager = new ListenerManager(PayActivity.this);
        listenerManager.getInstance(PayActivity.this).payUpdata();
    }
    private void payFail() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                wait.setVisibility(View.INVISIBLE);
                result.setVisibility(View.VISIBLE);
                result.setText("商品已卖光");

                num.setVisibility(View.VISIBLE);
                txt.setVisibility(View.VISIBLE);
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 3; i >= 0; i--) {
                    count = i;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (count > 0) {
                                num.setText(count + "");
                            } else {
                                finish();
                            }

                        }
                    });
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void payResult() {
        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
        wait.setVisibility(View.INVISIBLE);
        result.setVisibility(View.VISIBLE);
        result.setText("支付成功");
        payPrice.setVisibility(View.VISIBLE);
        payPrice.setText(orderDTO.getOrderPrice() + " ￥");

        num.setVisibility(View.VISIBLE);
        txt.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 5; i >= 0; i--) {
                    count = i;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (count > 0) {
                                num.setText(count + "");
                            } else {
                                Intent intent = new Intent(PayActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            }

                        }
                    });
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        ListenerManager listenerManager = new ListenerManager(PayActivity.this);
        listenerManager.getInstance(PayActivity.this).payUpdata();
    }

    private void savaOrder() {
        orderDTO.setOrderStatus(1);
        Log.e("buy",orderDTO.toString());
        OkHttpClient okHttpClient = new OkHttpClient();
        JSONObject object = new JSONObject();
        try {
            object.put("userId", orderDTO.getUserId());
            object.put("sellerId", orderDTO.getSellerId());
            object.put("goodsId", orderDTO.getGoodsId());
            object.put("orderStatus", orderDTO.getOrderStatus());
            object.put("orderPrice", orderDTO.getOrderPrice());
            object.put("receiveAddress", orderDTO.getReceiveAddress());
            object.put("address", orderDTO.getAddress());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("pay", object.toString());
        RequestBody body = RequestBody.create(type, "" + object.toString());

        Request request = new Request.Builder()
                .url(Constant.ADDORDER)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("pay","订单提交失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("pay","订单提交成功：" + result);
                String str = result.substring(0,4);
                orderId = result.substring(4, result.length());
                Log.e("pay", "str：" + str + " orderId:" + orderId);
                if ("添加成功".equals(str)) {
                    Message message = new Message();
                    message.what = SDK_PAY_RESULT;
                    mHandler.sendMessage(message);
                } else {
                    payFail();
                }
            }
        });
    }

    /**
     * 支付宝支付业务示例
     */
    public void payV2() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            showAlert(this, getString(R.string.error_missing_appid_rsa_private));
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);

        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, price + "");
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private static void showAlert(Context ctx, String info) {
        showAlert(ctx, info, null);
    }

    private static void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton(R.string.confirm, null)
                .show();
    }

    private static void showToast(Context ctx, String msg) {
        Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
    }

    private static String bundleToString(Bundle bundle) {
        if (bundle == null) {
            return "null";
        }
        final StringBuilder sb = new StringBuilder();
        for (String key: bundle.keySet()) {
            sb.append(key).append("=>").append(bundle.get(key)).append("\n");
        }
        return sb.toString();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }
}